<?php
namespace cosocket\system\database\pools;

use cosocket\system\database\wrappers\RedisWrapper;

class RedisPool
{
    private static $instances = array();
    private static $config;
    private static function getRedisConfig()
    {
        if (self::$config === null) {
            $configFile = PROJ_PATH. "/config/redis.php";
            if (!file_exists($configFile)) {
                throw new \Exception("Redis配置文件不存在");
            }
            self::$config = include($configFile);
        }
        return self::$config;
    }

    public static function put($name,$rediscli)
    {
        self::$instances[$name]->put($rediscli);
    }

    public static function getInstance($name)
    {
        $keyName = $name;
        if(isset(self::$instances[$name])){
            $rediscli = self::$instances[$keyName]->get();
            return new RedisWrapper($name,$rediscli);
        }

        //获取配置
        $redisconig = self::getRedisConfig();

        if(empty($redisconig[$name])){
            throw new \Exception(" 找不到redis数据的配置{$name}");
        }
        $dbconfig = $redisconig[$name];

        $host = $dbconfig['host'];
        $port = 6379;
        if(!empty($dbconfig['port'])){
            $port=$dbconfig['port'];
        }

        $timeout = 0;
        if(!empty($dbconfig['timeout'])){
            $timeout=$dbconfig['timeout'];
        }

        $reserved = "";
        if(!empty($dbconfig['reserved'])){
            $reserved=$dbconfig['reserved'];
        }

        $retry_interval = 0;
        if(!empty($dbconfig['retry_interval'])){
            $retry_interval=$dbconfig['retry_interval'];
        }

        $read_timeout = 0;
        if(!empty($dbconfig['read_timeout'])){
            $read_timeout=$dbconfig['read_timeout'];
        }

        $auth = "";
        if(!empty($dbconfig['auth'])){
            $auth=$dbconfig['auth'];
        }

        $dbIndex = 0;
        if(!empty($dbconfig['dbIndex'])){
            $dbIndex=$dbconfig['dbIndex'];
        }

        $poolsize = 64;
        if(!empty($dbconfig['poolsize'])){
            $poolsize=$dbconfig['poolsize'];
        }

        $pool = new \Swoole\Database\RedisPool((new \Swoole\Database\RedisConfig)
                ->withHost($host)
                ->withPort($port)
                ->withTimeout($timeout)
                ->withReserved($reserved)
                ->withRetryInterval($retry_interval)
                ->withReadTimeout($read_timeout)
                ->withAuth($auth)
                ->withDbIndex($dbIndex)
            ,$poolsize);
        self::$instances[$keyName] = $pool;
        $rediscli = self::$instances[$keyName]->get();
        return new RedisWrapper($name,$rediscli);
    }

}